<script setup lang="ts">
import {onMounted, ref, watch} from 'vue'
import QuestionBasicInfo from './components/QuestionBasicInfo.vue'
import QuestionSettings from './components/QuestionSettings.vue'
import JudgeInfo from './components/JudgeInfo.vue'
import {QuestionControllerService, TestCase, UpdateQuestionVO} from "../../../../generated";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRoute, useRouter} from "vue-router";
import QuestionTypeSelector from "@/views/question/addQuestion/components/QuestionTypeSelector.vue";
import {QuestionType} from "@/views/question/addQuestion/types/questionTypes.ts";
import {GenerateTypes} from "@/views/question/addQuestion/types/generatetTypes.ts";

let route = useRoute();
let router = useRouter();

// 创建表单对象
const form = ref<UpdateQuestionVO>({
  title: '',
  content: '',
  type: QuestionType.PROGRAMMING,
  difficulty: 0,
  language: [] as string[],
  testCaseList: [] as TestCase[],
  timeLimit: 400,
  memoryLimit: 65535,
  tagList: [] as string[]
})

const isEditorFullscreen = ref(false)

const currentQuestionType = ref(QuestionType.PROGRAMMING)
const testCasesRef = ref()

watch(() => form.value.type, (newType) => {
  if (newType !== undefined) {
    currentQuestionType.value = newType;
  }
})

const checkAvailable = () => {
  // 检查必填项
  if (!form.value.title) {
    ElMessage.error("标题不能为空");
    return false;
  }
  if (form.value.type === undefined) {
    ElMessage.error("请选择题目类型");
    return false;
  }
  if (form.value.difficulty === undefined) {
    ElMessage.error("请选择难度");
    return false;
  }

  // 检查分数
  if (form.value.type !== QuestionType.PROGRAMMING) {
    if (!form.value.score || form.value.score <= 0) {
      ElMessage.error("分数需大于零");
      return false;
    }
  }

  // 编程题特殊检查
  if (form.value.type === QuestionType.PROGRAMMING) {
    if (!form.value.language || form.value.language.length === 0) {
      ElMessage.error("至少需要支持一种编程语言");
      return false;
    }
    if (form.value.testCaseList && form.value.testCaseList.length > 0) {
      for (const testCase of form.value.testCaseList) {
        if (!testCase.score || testCase.score <= 0) {
          ElMessage.error("测试用例的分数需大于零");
          return false;
        }
      }
    }
  }

  // 选择题特殊检查
  if (form.value.type === QuestionType.MULTIPLE_CHOICE) {
    if (!form.value.choiceOptionList || form.value.choiceOptionList.length === 0) {
      ElMessage.error("选择题至少需要一个选项");
      return false;
    }
    const hasCorrectAnswer = form.value.choiceOptionList.some(option => option.isCorrect);
    if (!hasCorrectAnswer) {
      ElMessage.error("选择题至少需要一个正确答案");
      return false;
    }
  }

  return true;
}

const handleSubmit = async () => {
  // 根据题目类型，从JudgeInfo组件获取相应数据
  if (testCasesRef.value) {
    const answerData = testCasesRef.value.getAnswerData();
    // 根据题目类型合并数据
    switch (form.value.type) {
      case QuestionType.PROGRAMMING:
        // 编程题保持不变，使用testCase
        break;
      case QuestionType.MULTIPLE_CHOICE:
        // 选择题填入options数组
        form.value.choiceOptionList = answerData.choiceOptionList;
        form.value.score = answerData.score;
        break;
      case QuestionType.JUDGEMENT:
        // 判断题填入isCorrect
        form.value.isCorrect = answerData.isCorrect;
        form.value.analysis = answerData.analysis;
        form.value.score = answerData.score;
        break;
      case QuestionType.FILL_BLANK:
        // 填空题填入answer数组
        form.value.answer = answerData.answers;
        form.value.analysis = answerData.analysis;
        form.value.score = answerData.score;
        break;
      case QuestionType.COMPREHENSIVE:
        // 综合题填入referenceAnswer
        form.value.referenceAnswer = answerData.referenceAnswer;
        form.value.score = answerData.score;
        break;
    }
  }
  let check = checkAvailable();
  if (!check) {
    return;
  }
  let res = await QuestionControllerService.updateQuestionUsingPost(form.value);
  if (res.code === 0) {
    ElMessage.success("更新成功")
    await router.push('/question/detail/' + form.value.id)
  } else {
    ElMessage.error(res.message)
  }
}

const handleDelete = async () => {
  let res = await QuestionControllerService.deleteQuestionUsingPost({
    id: route.params.id as string
  });
  if (res.code === 0 && res.data) {
    ElMessage.success('删除成功')
    await router.push('/problem')
  } else {
    ElMessage.error(res.message)
  }
}

const open = () => {
  ElMessageBox.confirm(
      '是否确认删除?该操作无法撤销',
      '删除题目',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        handleDelete()
      })
}

onMounted(async () => {
  let res = await QuestionControllerService.getQuestionDetailByIdUsingGet(route.params.id as string);
  if (res.code === 0) {
    if (res.data) {
      form.value = res.data;
    }
  } else {
    ElMessage.error(res.message)
  }
})

const generateContent = async () => {
  let res = await QuestionControllerService.generateUsingPost({
    title: form.value.title,
    type: GenerateTypes.CONTENT
  });
  form.value.content = res.data.content
}

const generateTags = async () => {
  let res = await QuestionControllerService.generateUsingPost({
    title: form.value.title,
    content: form.value.content,
    type: GenerateTypes.TAGS
  });
  form.value.tagList = res.data.tagList
}

const generateTestCase = async () => {
  let res = await QuestionControllerService.generateUsingPost({
    title: form.value.title,
    content: form.value.content,
    type: GenerateTypes.TEST_CASE
  })
  form.value.testCaseList = res.data.testCaseList
}
</script>

<template>
  <div class="update-question-container" :class="{ 'editor-fullscreen': isEditorFullscreen }">
    <div class="page-header">
      <h2>更新题目</h2>
      <div>
        <el-button type="danger" @click="open">删除题目</el-button>
        <el-button type="primary" @click="handleSubmit">发布题目</el-button>
      </div>
    </div>

    <el-form
        ref="formRef"
        :model="form"
        label-position="top"
        class="question-form"
    >
      <QuestionBasicInfo
          ref="questionBasicInfoRef"
          v-model="form.title"
          v-model:content="form.content"
          v-model:question-type="form.type"
          :is-editor-fullscreen="isEditorFullscreen"
          @fullscreen-change="val => isEditorFullscreen = val"
          @generate-content="generateContent"
      />
      <QuestionTypeSelector
          v-model="form.type"
          :is-editor-fullscreen="isEditorFullscreen"
          :disabled="true"
      />
      <QuestionSettings
          v-model:difficulty="form.difficulty"
          v-model:language="form.language"
          v-model:timeLimit="form.timeLimit"
          v-model:memoryLimit="form.memoryLimit"
          v-model:tags="form.tagList"
          :type="form.type"
          @generate:tags="generateTags"
      />

      <JudgeInfo
          ref="testCasesRef"
          v-model:testCase="form.testCaseList"
          :question-type="currentQuestionType"
          :options="form.choiceOptionList"
          :is-correct="form.isCorrect"
          :analysis="form.analysis"
          :answers="form.answer"
          :reference-answer="form.referenceAnswer"
          :score="form.score"
          @generate:testCase="generateTestCase"
      />
    </el-form>
  </div>
</template>

<style scoped>
.update-question-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  position: relative;
  padding-left: 16px;
}

.page-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
}

.question-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
</style>
